import java.util.ArrayList;

/*
 * @lc app=leetcode.cn id=17 lang=java
 *
 * [17] 电话号码的字母组合
 */

// @lc code=start
// class Solution {
//     public List<String> letterCombinations(String digits) {
//         List<String> ans = new ArrayList<>();
//         String[] number = new String[]{
//             "","","abc","def","ghi","jkl",
//             "mno","pqrs","tuv","wxyz"};
//         //如果是用循环写的话，因为不能事先确定digits的位数，所以无法实现多层循环，所以用递归去做

//     }
// }

class Solution {
    //用递归去做
    public List<String> letterCombinations(String digits) {
        List<String> ans = new ArrayList<String>();
        if (digits.length() == 0) {
            return ans;
        }
        Map<Character, String> phoneMap = new HashMap<Character, String>() {{
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }};
        backtrack(ans, phoneMap, digits, 0, new StringBuilder());
        return ans;
    }

    public void backtrack(List<String> ans, Map<Character, String> phoneMap, String digits, int index, StringBuilder temp) {
        if (index == digits.length()) {//index是 digits的每个数字的位置
            ans.add(temp.toString());//这是递归结束条件，就是递归到最后了，就把存下来的temp给加入答案。
        } else {
            char digit = digits.charAt(index);
            String letters = phoneMap.get(digit);
            int lettersCount = letters.length();
            for (int i = 0; i < lettersCount; i++) {
                temp.append(letters.charAt(i));//加一个对应字母
                backtrack(ans, phoneMap, digits, index + 1, temp);//去递归，index+1即可
                temp.deleteCharAt(index);//把加的字母删了，准备
            }
        }
    }
}

// @lc code=end

